package com.victor.modular.system.controller;

import com.victor.common.annotion.Permission;
import com.victor.common.annotion.log.BussinessLog;
import com.victor.common.constant.Const;
import com.victor.common.constant.Dict;
import com.victor.common.constant.factory.ConstantFactory;
import com.victor.common.constant.state.ManagerStatus;
import com.victor.common.constant.tips.Tip;
import com.victor.common.controller.BaseController;
import com.victor.common.exception.BizExceptionEnum;
import com.victor.common.exception.BussinessException;
import com.victor.common.persistence.model.User;
import com.victor.core.log.LogObjectHolder;
import com.victor.core.shiro.ShiroKit;
import com.victor.core.util.ToolUtil;
import com.victor.modular.system.transfer.UserDto;
import com.victor.modular.system.warpper.UserWarpper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.naming.NoPermissionException;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 系统管理员控制器
 *
 * @author jiabin.Zhao
 * @Date 2017年1月11日 下午1:08:17
 */
@Controller
@RequestMapping("/mgr")
public class UserMgrController extends BaseController {

    private static String PREFIX = "/system/user/";

    /**
     * 跳转到查看用户列表的页面
     */
    @RequestMapping("")
    public String index(Model model) {

        //角色集合
        List<Map<String, Object>> roleList = null;
        roleList = this.roleDao.selectRoles(null);
        model.addAttribute("roleList", roleList);
        return PREFIX + "user.html";
    }

    /**
     * 跳转到添加用户的页面
     */
    @RequestMapping("/user_add")
    public String addView(Model model) {

        //角色集合
        List<Map<String, Object>> roleList = null;
        roleList = this.roleDao.selectRoles(null);
        model.addAttribute("roleList", roleList);
        return PREFIX + "user_add.html";
    }

    /**
     * 跳转到个人资料页面
     */
    @RequestMapping("/user_self")
    public String userSelf(Model model) {
        User user = this.userMapper.selectById(ShiroKit.getUser().getId());
        model.addAttribute("user", user);
        model.addAttribute("roleName", ConstantFactory.me().getSingleRoleName(Integer.valueOf(user.getRoleid())));
        model.addAttribute("statusName", ConstantFactory.me().getStatusName(user.getStatus()));
        return PREFIX + "user_self.html";
    }

    /**
     * 跳转到编辑用户页面
     */
    @Permission
    @RequestMapping("/user_edit/{userId}")
    public String editView(@PathVariable Integer userId, Model model) {
        if (ToolUtil.isEmpty(userId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        //角色集合
        List<Map<String, Object>> roleList = null;
        roleList = this.roleDao.selectRoles(null);
        model.addAttribute("roleList", roleList);
        User user = this.userMapper.selectById(userId);
        model.addAttribute(user);

        return PREFIX + "user_edit.html";
    }

    /**
     * 跳转到修改密码界面
     */
    @RequestMapping("/user_chpwd")
    public String chPwd() {
        return PREFIX + "user_chpwd.html";
    }

    /**
     * 修改当前用户的密码
     */
    @RequestMapping("/changePwd")
    @ResponseBody
    public Object changePwd(@RequestParam String oldPwd, @RequestParam String newPwd, @RequestParam String rePwd) {
        if (!newPwd.equals(rePwd)) {
            throw new BussinessException(BizExceptionEnum.TWO_PWD_NOT_MATCH);
        }
        Integer userId = ShiroKit.getUser().getId();
        User user = userMapper.selectById(userId);
        String oldMd5 = ShiroKit.md5(oldPwd, user.getSalt());
        if (user.getPassword().equals(oldMd5)) {
            user.setClearpwd(newPwd);
            String newMd5 = ShiroKit.md5(newPwd, user.getSalt());
            user.setPassword(newMd5);
            user.updateById();
            return SUCCESS_TIP;
        } else {
            throw new BussinessException(BizExceptionEnum.OLD_PWD_NOT_RIGHT);
        }
    }

    /**
     * 查询用户列表
     */
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(required = false) String name, @RequestParam(required = false) String beginTime,
                       @RequestParam(required = false) String endTime,
                       @RequestParam(required = false) Integer roleid) {

        List<Map<String, Object>> users = managerDao.selectUsers(name, beginTime, endTime, ManagerStatus.OK.getCode(), roleid);
        return new UserWarpper(users).warp();
    }

    /**
     * 添加用户
     */
    @RequestMapping("/add")
    @BussinessLog(value = "添加用户", key = "account", dict = Dict.USER_DICT)
    @Permission
    @ResponseBody
    public Tip add(@Valid UserDto userDto, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        this.userService.add(userDto);
        return SUCCESS_TIP;
    }

    /**
     * 修改用户
     *
     * @throws NoPermissionException
     */
    @RequestMapping("/edit")
    @BussinessLog(value = "修改用户", key = "account", dict = Dict.USER_DICT)
    @Permission
    @ResponseBody
    public Tip edit(@Valid UserDto userDto, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        LogObjectHolder.me().set(userMapper.selectById(userDto.getId()));
        this.userService.update(userDto);
        return SUCCESS_TIP;
    }

    /**
     * 删除用户
     */
    @RequestMapping("/delete/{id}")
    @Permission
    @ResponseBody
    public Object delete(@PathVariable Integer id) throws Exception {
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        this.userService.delete(id);
        return SUCCESS_TIP;
    }

    /**
     * 修改用户 个人信息
     *
     * @throws NoPermissionException
     */
    @RequestMapping("/self")
    @BussinessLog(value = "修改个人资料", key = "account", dict = Dict.USER_DICT)
    @ResponseBody
    public Tip self(@Valid UserDto userDto, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        Integer userId = ShiroKit.getUser().getId();
        User user = userMapper.selectById(userId);
        LogObjectHolder.me().set(user);
        user.setName(userDto.getName());
        user.setEmail(userDto.getEmail());
        user.setBirthday(userDto.getBirthday());
        user.setPhone(userDto.getPhone());
        user.setSex(userDto.getSex());
        user.setUpdatetime(new Date());
        user.setUpdateUserId(userId);
        user.setAvatarUrl(userDto.getAvatarUrl());
        this.userMapper.updateById(user);
        //删除缓存
        clearAllCache();
        return SUCCESS_TIP;
    }

    /**
     * 查看用户详情
     */
    @RequestMapping("/view/{userId}")
    @ResponseBody
    public User view(@PathVariable Integer userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return this.userMapper.selectById(userId);
    }

    /**
     * 重置用户的密码
     */
    @RequestMapping("/reset")
    @BussinessLog(value = "重置密码", key = "userId", dict = Dict.USER_DICT)
    @Permission
    @ResponseBody
    public Tip reset(@RequestParam Integer userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        User user = this.userMapper.selectById(userId);
        user.setClearpwd(Const.DEFAULT_PWD);
        user.setSalt(ShiroKit.getRandomSalt(5));
        user.setPassword(ShiroKit.md5(Const.DEFAULT_PWD, user.getSalt()));
        this.userMapper.updateById(user);
        return SUCCESS_TIP;
    }

    /**
     * 冻结用户
     */
    @RequestMapping("/freeze")
    @BussinessLog(value = "冻结用户", key = "userId", dict = Dict.USER_DICT)
    @Permission
    @ResponseBody
    public Tip freeze(@RequestParam Integer userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        // 不能冻结超级管理员
        if (userId.equals(Const.ADMINISTRATOR_ID)) {
            throw new BussinessException(BizExceptionEnum.CANT_FREEZE_ADMIN);
        }
        this.managerDao.setStatus(userId, ManagerStatus.FREEZED.getCode());
        return SUCCESS_TIP;
    }

    /**
     * 解除冻结用户
     */
    @RequestMapping("/unfreeze")
    @BussinessLog(value = "解除冻结用户", key = "userId", dict = Dict.USER_DICT)
    @Permission
    @ResponseBody
    public Tip unfreeze(@RequestParam Integer userId) {
        if (ToolUtil.isEmpty(userId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        this.managerDao.setStatus(userId, ManagerStatus.OK.getCode());
        return SUCCESS_TIP;
    }

    /**
     * 跳转用户详情
     */
    @RequestMapping("/detail/{userId}")
    public String detail(@PathVariable Integer userId, Model model) {
        if (ToolUtil.isEmpty(userId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        User user = this.userMapper.selectById(userId);
        model.addAttribute(user);
        //角色
        String roleid = user.getRoleid();
        String roleName = "";
        if (ToolUtil.isNotEmpty(roleid)) {
            roleName = ConstantFactory.me().getRoleName(roleid);
        }
        model.addAttribute("roleName", roleName);
        //性别
        Integer sex = user.getSex();
        String sexName = "";
        if (ToolUtil.isNotEmpty(sex)) {
            sexName = ConstantFactory.me().getSexName(sex);
        }
        model.addAttribute("sexName", sexName);
        //创建人
        String createUserName = "";
        Integer createUserId = user.getCreateUserId();
        if (ToolUtil.isNotEmpty(createUserId)) {
            createUserName = ConstantFactory.me().getUserNameById(createUserId);
        }
        model.addAttribute("createUserName", createUserName);
        //修改人
        String updateUserName = "";
        Integer updateUserId = user.getUpdateUserId();
        if (ToolUtil.isNotEmpty(updateUserId)) {
            updateUserName = ConstantFactory.me().getUserNameById(updateUserId);
        }
        model.addAttribute("updateUserName", updateUserName);
        //最后登录时间
        model.addAttribute("lastLoginTime", ConstantFactory.me().getLastLoginTime(user.getId()));
        return PREFIX + "user_detail.html";
    }


}
